package com.sambo.inspection.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonElement;
import com.lzy.okgo.model.HttpParams;
import com.sambo.inspection.R;
import com.sambo.inspection.activity.support.BaseActivity;
import com.sambo.inspection.bean.GlobleBean;
import com.sambo.inspection.bean.LoginResponseBean;
import com.sambo.inspection.component.ZnkProgressDialog;
import com.sambo.inspection.http.HttpClient;
import com.sambo.inspection.http.HttpResponseHandler;
import com.sambo.inspection.http.Urls;
import com.sambo.inspection.util.JsonUtil;
import com.sambo.inspection.util.SpUtil;

public class LoginActivity extends BaseActivity {

    public static final String TAG = LoginActivity.class.getSimpleName();
    private static final int CODE_SET_SERVER = 1;

    TextView tvSetServer;
    EditText etPhoneValue;
    EditText etPasswordValue;

    ImageView ivDeletePhone;
    ImageView ivDeletePassword;

    TextView tvLoginBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.w(TAG, "onCreate()");

        // 加载布局
        setContentView(R.layout.activity_login);

        tvSetServer = findViewById(R.id.tv_set_server);
        etPhoneValue = findViewById(R.id.et_phone_value);
        etPasswordValue = findViewById(R.id.et_password_value);
        ivDeletePhone = findViewById(R.id.iv_delete_phone);
        ivDeletePassword = findViewById(R.id.iv_delete_password);
        tvLoginBtn = findViewById(R.id.tv_login_btn);

        tvSetServer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this, ChangeInfoActivity.class);
                intent.putExtra("title", "设置服务器地址");
                intent.putExtra("content", Urls.API_SERVER_HOST);
                startActivityForResult(intent, CODE_SET_SERVER);
            }
        });

        tvLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestLogin(etPhoneValue.getText().toString(), etPasswordValue.getText().toString());
            }
        });

        etPhoneValue.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    ivDeletePhone.setVisibility(View.VISIBLE);
                    if (etPasswordValue.getText().toString().length() > 0) {
                        tvLoginBtn.setEnabled(true);
                    } else {
                        tvLoginBtn.setEnabled(false);
                    }
                } else {
                    ivDeletePhone.setVisibility(View.INVISIBLE);
                    tvLoginBtn.setEnabled(false);
                }
            }
        });

        etPasswordValue.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    ivDeletePassword.setVisibility(View.VISIBLE);
                    if (etPhoneValue.getText().toString().length() > 0) {
                        tvLoginBtn.setEnabled(true);
                    } else {
                        tvLoginBtn.setEnabled(false);
                    }
                } else {
                    ivDeletePassword.setVisibility(View.INVISIBLE);
                    tvLoginBtn.setEnabled(false);
                }
            }
        });

        // 删除手机号
        ivDeletePhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etPhoneValue.setText("");
            }
        });

        // 删除密码文本
        ivDeletePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etPasswordValue.setText("");
            }
        });

        etPhoneValue.setText(SpUtil.getUserName());
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == CODE_SET_SERVER) {
                Urls.API_SERVER_HOST = data.getStringExtra("content");
            }
        }
    }

    private void requestLogin(final String userName, final String password) {
        ZnkProgressDialog dialog = ZnkProgressDialog.createLoadingDialog(this, "登录中...");
        dialog.show();
        // 调用登录API
        HttpParams params = new HttpParams();
        params.put("username", userName);
        params.put("password", password);

        HttpClient.post(LoginActivity.this, Urls.API_SERVER_HOST + Urls.LOGIN, params,
                new HttpResponseHandler() {
                    @Override
                    public void onInnovationSuccess(JsonElement value) {
                        super.onInnovationSuccess(value);
                        LoginResponseBean bean = JsonUtil.toObj(value.toString(), LoginResponseBean.class);

                        if (bean != null) {
                            SpUtil.setUserName(userName);
                            SpUtil.setPassword(password);

                            GlobleBean.getInstance().setUserID(SpUtil.getUserID(userName));
                            GlobleBean.getInstance().setUserName(userName);
                            GlobleBean.getInstance().setAccessToken(bean.getAccess_token());
                            GlobleBean.getInstance().setNickName(SpUtil.getNickName(userName));
                            GlobleBean.getInstance().setPhone(SpUtil.getPhone(userName));
                            GlobleBean.getInstance().setDeptID(SpUtil.getDeptID(userName));
                            GlobleBean.getInstance().setLastMessageTS(SpUtil.getLastMessageTS(userName));

                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                        } else {
                            Toast.makeText(LoginActivity.this, "解析数据错误", Toast.LENGTH_LONG).show();
                        }


                    }

                    @Override
                    public void onInnovationFinish() {
                        super.onInnovationFinish();
                        dialog.dismiss();
                    }
                }, new HttpClient.NetworkUnavailableListener() {
                    @Override
                    public void networkUnavailable() {
                        dialog.dismiss();
                        Toast.makeText(LoginActivity.this, "网络连接异常，请检查您的网络", Toast.LENGTH_LONG).show();
                    }
                });
    }
}
